
#include <signal.h>
#include <time.h>
#include "timer_interface.h"
#include "../debug.h"


int TimerInf_Create(timer_t *pTimerId, void (*pFuncCallback)(union sigval), void *pParam)
{
    struct sigevent sigEvt;

    if(*pTimerId != NULL)
    {
        PRINT_DEBUG("Timer already exist");
        return 0;
    }
    
    sigEvt.sigev_notify = SIGEV_THREAD;
    sigEvt.sigev_notify_function = pFuncCallback;
    sigEvt.sigev_value.sival_ptr = pParam;
    sigEvt.sigev_notify_attributes = NULL;
    if(timer_create(CLOCK_MONOTONIC, &sigEvt, pTimerId) == -1)
    {
        PERROR("timer_create");
        return -1;
    }
    
    return 0;
}


int TimerInf_Delete(timer_t *pTimerId)
{
    if(*pTimerId == NULL)
    {
        return 0;
    }

    if(timer_delete(*pTimerId) == -1)
    {
        PERROR("timer_delete");
        return -1;
    }

    *pTimerId = NULL;
    PRINT_DEBUG("Timer delete");

    return 0;
}


int TimerInf_Start(timer_t timerId, time_t sec, long nsec, timerType_t type)
{
    struct itimerspec timerVal;

    timerVal.it_value.tv_sec = sec;
    timerVal.it_value.tv_nsec = nsec;

    if(type == TIMER_ONCE)
    {
        timerVal.it_interval.tv_sec = 0;
        timerVal.it_interval.tv_nsec = 0;
    }
    else if(type == TIMER_CYCLE)
    {
        timerVal.it_interval.tv_sec = sec;
        timerVal.it_interval.tv_nsec = nsec;
    }
    else
    {
        PRINT_WARN("type[%d]", type);
        return -1;
    }

    if(timer_settime(timerId, 0, &timerVal, NULL) == -1)
    {
        PERROR("timer_settime");
        return -2;
    }
    
    return 0;
}

